/* eslint-disable no-undef */
import { reactive } from 'vue';
import wx from 'weixin-js-sdk';
import { device, hasOwn, type } from './functions';
// import request from './request-set';

// 兼容wx部分接口调用失败问题（原因是wxjssdk中使用了部分全局变量wx，但是wx并未在全局注册）
if (!hasOwn('wx')) {
  window.wx = wx;
}

// 微信可用接口
export const jsApiList = [
  'checkJsApi',
  'onMenuShareTimeline',
  'onMenuShareAppMessage',
  'onMenuShareQQ',
  'onMenuShareWeibo',
  'onMenuShareQZone',
  'hideMenuItems',
  'showMenuItems',
  'hideAllNonBaseMenuItem',
  'showAllNonBaseMenuItem',
  'translateVoice',
  'startRecord',
  'stopRecord',
  'onVoiceRecordEnd',
  'playVoice',
  'onVoicePlayEnd',
  'pauseVoice',
  'stopVoice',
  'uploadVoice',
  'downloadVoice',
  'chooseImage',
  'previewImage',
  'uploadImage',
  'downloadImage',
  'getLocalImgData',
  'getNetworkType',
  'openLocation',
  'getLocation',
  'hideOptionMenu',
  'showOptionMenu',
  'closeWindow',
  'scanQRCode',
  'chooseWXPay',
  'openProductSpecificView'
];

// 微信可用开放标签
export const openTagList = [];

/**
 * 加载微信动作通知，必须在 initWx 执行后使用，否则不生效
 * catch分支谨慎使用
 *
 * @return Promise.resolve(wx)
 * @return Promise.reject(res)
 */
export function wxLoader () {
  return new Promise((resolve, reject) => {
    wx.ready(() => {
      resolve(wx);
    });

    wx.error(res => {
      reject(res);
    });
  });
}

/**
 * 获取服务器配置当前页面的微信sdk参数
 *
 * 失败时不返回任何提示
 */
// export function getAccess () {
//   const requestUrl = location.origin + location.pathname + location.search;

//   return request({
//     url: '/shijiwxy/wechat/portal/getWxJsConfig.json',
//     data: {
//       url: requestUrl
//     }
//   })
//     .then(res => {
//       return res.data;
//     });
// }

/**
 * 微信功能：隐藏所有右上角菜单可隐藏内容
 */
export function hideMenu () {
  //wx.hideAllNonBaseMenuItem();
  // 调试时打开，复制当前地址
  wx.showMenuItems({
    menuList: ['menuItem:copyUrl']
  });
}

/**
 * 注入微信功能
 *
 * @return Promise
 */
// export function initWx (options = {}) {
//   options = Object.assign({
//     jsApiList
//   }, options);

//   return getAccess().then(access => {
//     wx.config({
//       beta: true,
//       debug: false,
//       appId: access.appId,
//       timestamp: access.timestamp,
//       nonceStr: access.nonceStr,
//       signature: access.signature,
//       jsApiList: options.jsApiList
//     });

//     return wxLoader().then(wx => {
//       hideMenu();
//     });
//   });
// }

/**
 * 打开微信系统图片预览
 * @param {array} images 图片预览列表
 * @param {number|string} currentIndex 图片列表中的位置号或图片地址
 */
export function imagePreview (images = [], currentIndex = 0) {
  let current;

  if (typeof currentIndex === 'string') {
    current = currentIndex;
  } else {
    current = images[currentIndex];
  }
  WelkinJSBridge.invoke('imagePreview', {
    current: current,
    urls: images
  }, function (res) {
    // console.log(res.err_msg);
  });
}

export function getServerIds (localFiles) {
  if (type(localFiles) !== 'array') {
    localFiles = [localFiles];
  }

  const files = [];

  const local2Remote = function (callback, fail, index = 0) {
    if (localFiles[index]) {
      const localFile = localFiles[index];

      wxLoader()
        .then(wx => {
          wx.uploadImage({
            localId: localFile.localId,

            // 1.2.1：临时调整微信8.0.7调用bug
            isShowProgressTips: 1,
            // isShowProgressTips: 0,

            success: res => {
              const serverId = res.serverId;

              localFile.serverId = serverId;

              files.push(localFile);

              local2Remote(callback, fail, index + 1);
            },

            fail: function (error) {
              fail(error);
            }
          });
        });
    } else {
      callback && callback(files);
    }
  };

  return new Promise((resolve, reject) => {
    local2Remote(files => {
      resolve(files);
    }, error => {
      reject(error);
    });
  });
}

/**
 * 使用微信系统，获取图片serverid列表
 *
 * @param {object|function} uploadOptions 上传图片参数
 */
export function chooseWxImage (uploadOptions = {}) {
  let options = {
    count: 9,
    // 可以指定是原图original还是压缩图compressed，默认二者都有
    sizeType: ['compressed'],
    // 可以指定来源是相册album还是相机camera，默认二者都有
    sourceType: ['album'],
    // 上传前执行
    beforeUpload (localIds) {
      return localIds;
    },
    // 上传全部完毕之后执行
    done (files) { /*  */ }
  };
  // 当只传一个function时，视为使用默认参数，function为完毕事件
  if (type(options) === 'function') {
    options.success = uploadOptions;
    uploadOptions = undefined;
  }
  if (uploadOptions) {
    options = Object.assign(options, uploadOptions);
  }
  options.success = res => {
    localIdLinks(res.localIds).then(result => {
      let localFiles = result.map(item => item);
      // 上传前处理
      if (options.beforeUpload) {
        localFiles = options.beforeUpload(localFiles);
      }
      // 上传远程服务器
      setTimeout(() => {
        getServerIds(localFiles).then(files => {
          options.done && options.done(files);
        });
      }, 400);
    });
  };

  // 打开相册
  return wxLoader().then(wx => {
    wx.chooseImage(options);
  });
}

/**
 * 获取由于ios不支持localid预览问题。当预览时调用这个方法，当非ios调用时不会转义
 * 如果包含content并传入到vant组件，vant会优先将content当做预览图片使用
 */
export function localIdLinks (localIds = []) {
  const result = [];
  if (device() !== 'ios') {
    localIds.map(localId => {
      result.push(reactive({
        localId,
        content: localId
      }));
    });
    return Promise.resolve(result);
  }

  // 一个一个来，并发调会出错
  const getShowLInk = (success, i = 0) => {
    const localId = localIds[i];
    if (!localId) {
      return success && success();
    }
    wx.getLocalImgData({
      localId,
      success (res) {
        result.push(reactive({
          localId,
          content: res.localData
        }));
        getShowLInk(success, i + 1);
      }
    });
  };

  return new Promise(resolve => {
    getShowLInk(() => {
      resolve(result);
    });
  });
}
